package stack;

import java.util.Arrays;
import java.util.Stack;

public class MyStack {
    private int[] elem;
    private int usedSize;
    private static final int DEFAULT_CAPACITY = 10;
    public MyStack() {
        this.elem = new int[DEFAULT_CAPACITY];
    }

    public void push(int val) {//在栈中插入数据
        if(isFull()) {//如果满了就扩容
            elem = Arrays.copyOf(elem, 2*elem.length);
        }
        elem[this.usedSize] = val;
        this.usedSize++;
    }

    public boolean isFull() {//是否满了
        return usedSize == elem.length;
    }

    public int pop() {//获取栈顶元素并删除
        int top = elem[this.usedSize - 1];
        //删除栈顶元素
        if(isEmpty()) {
            throw  new EmptyException();
        }
        usedSize--;
        return top;
    }

    private boolean isEmpty() {
        return usedSize == 0;
    }

    public int peek() {
        if(isEmpty()) {
            throw  new EmptyException();
        }
        return elem[this.usedSize - 1];
    }

    //逆波兰表达式求值
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for(String s : tokens) {
            if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
                //如果是操作符,就从栈顶选两个元素
                int num2 = stack.pop();
                int num1 = stack.pop();
                switch (s) {
                    case "+":
                        stack.push(num1 + num2);
                        break;
                    case "-":
                        stack.push(num1 - num2);
                        break;
                    case "*":
                        stack.push(num1 * num2);
                        break;
                    case "/":
                        stack.push(num1 / num2);
                        break;
                }
            } else {//如果是数字就入栈
                stack.push(Integer.parseInt(s));
            }
        }
        return stack.pop();
    }

    //给出两个序列，第一个序列是栈的压入序列，判断第二个序列有没有可能是栈的弹出序列
    public boolean IsProper(int [] pushA, int [] popA) {
        Stack<Integer> stack  = new Stack<>();
        int j = 0;
        for (int i = 0; i < pushA.length; i++) {
            stack.push(pushA[i]);
            while(!stack.empty() && j < popA.length && stack.peek() == popA[j]) {
                stack.pop();
                j++;
            }
        }
        return stack.empty();
    }

    //最小栈

}
